package com.wms.service.impl;

import com.wms.entity.StorePurchase;
import com.wms.entity.StorePurchaseDTO;
import com.wms.enums.ReturnStatus;
import com.wms.mapper.StorePurchaseMapper;
import com.wms.service.StorePurchaseService;
import com.wms.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author TianWenHe
 * @date 2025/4/27
 * @desc
 */
@Service
public class StorePurchaseServiceImpl implements StorePurchaseService {
    @Autowired
    private StorePurchaseMapper storePurchaseMapper;
    private static final String IMAGE_PREFIX = "https://jinghaiyang.oss-cn-beijing.aliyuncs.com/app/upload/";

    @Override
    public List<StorePurchase> find(StorePurchaseDTO storePurchaseDTO) {
        return storePurchaseMapper.find(storePurchaseDTO);
    }

    @Override
    public Long add(StorePurchase storePurchase) {
        // 处理图片URL前缀
        if (storePurchase.getImage() != null && storePurchase.getImage().startsWith(IMAGE_PREFIX)) {
            storePurchase.setImage(storePurchase.getImage().replace(IMAGE_PREFIX, ""));
        }
        // 统一设置创建时间
        storePurchase.setCreateTime(DateUtils.addFixedEightHours(new Date()));

        storePurchaseMapper.add(storePurchase);
        return storePurchase.getId();
    }

    @Override
    public void update(StorePurchase storePurchase) {
        // 处理图片URL前缀
        if (storePurchase.getImage() != null && storePurchase.getImage().startsWith(IMAGE_PREFIX)) {
            storePurchase.setImage(storePurchase.getImage().replace(IMAGE_PREFIX, ""));
        }
        // 如果状态为“待入库”且没有设置receiving_time，则设置receiving_time
        if (storePurchase.getStatus().equals(ReturnStatus.TO_BE_STORED.getDescription()) && storePurchase.getReceivingTime() == null) {
            storePurchase.setReceivingTime(DateUtils.addFixedEightHours(new Date()));
        }

        // 如果状态为“部分入库”且没有设置storage_time，则设置storage_time
        if (storePurchase.getStatus().equals(ReturnStatus.PARTIALLY_STORED.getDescription()) && storePurchase.getStorageTime() == null) {
            storePurchase.setStorageTime(DateUtils.addFixedEightHours(new Date()));
        }

        storePurchaseMapper.update(storePurchase);
    }

    @Override
    public void delete(List<Long> ids) {
        storePurchaseMapper.delete(ids);
    }

    @Override
    public void insertBatch(List<StorePurchase> storePurchases) {
        // 统一设置创建时间
        for (StorePurchase storePurchase : storePurchases) {
            storePurchase.setCreateTime(DateUtils.addFixedEightHours(new Date()));
        }
        storePurchaseMapper.insertBatch(storePurchases);
    }
}
